home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / GENCSRC.ZIP / DYNLINK.C < prev    next >
C/C++ Source or Header  |  1987-11-21  |  2KB  |  55 lines

  1.                                           /* Chapter 12 - Program 3 */
  2. #include "stdio.h"    /* this is needed only to define the NULL     */
  3. #define RECORDS 6
  4.  
  5. main()
  6. {
  7. struct animal {
  8.    char name[25];       /* The animals name                         */
  9.    char breed[25];      /* The type of animal                       */
  10.    int age;             /* The animals age                          */
  11.    struct animal *next; /* a pointer to another record of this type */
  12. } *point, *start, *prior; /* this defines 3 pointers, no variables  */
  13. int index;
  14.  
  15.                        /* the first record is always a special case */
  16.  
  17.    start = (struct animal *)malloc(sizeof(struct animal));
  18.    strcpy(start->name,"General");
  19.    strcpy(start->breed,"Mixed Breed");
  20.    start->age = 4;
  21.    start->next = NULL;
  22.    prior = start;
  23.        /* a loop can be used to fill in the rest once it is started */
  24.  
  25.    for (index = 0;index < RECORDS;index++) {
  26.       point = (struct animal *)malloc(sizeof(struct animal));
  27.       strcpy(point->name,"Frank");
  28.       strcpy(point->breed,"Laborador Retriever");
  29.       point->age = 3;
  30.       prior->next = point;  /* point last "next" to this record */
  31.       point->next = NULL;   /* point this "next" to NULL        */
  32.       prior = point;        /* this is now the prior record     */
  33.    }
  34.  
  35.        /* now print out the data described above */
  36.  
  37.    point = start;
  38.    do {
  39.       prior = point->next;
  40.       printf("%s is a %s, and is %d years old.\n", point->name,
  41.               point->breed, point->age);
  42.       point = point->next;
  43.    } while (prior != NULL);
  44.  
  45.        /* good programming practice dictates that we free up the */
  46.        /* dynamically allocated space before we quit.            */
  47.  
  48.    point = start;            /* first block of group      */
  49.    do {
  50.       prior = point->next;   /* next block of data        */
  51.       free(point);           /* free present block        */
  52.       point = prior;         /* point to next             */
  53.    } while (prior != NULL);  /* quit when next is NULL    */
  54. }
  55.